package controllers

import (
	"admin-glm-go/internal/config"
	"admin-glm-go/internal/middleware"
	"admin-glm-go/internal/models"
	"admin-glm-go/internal/response"
	"admin-glm-go/internal/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// LoginRequest 登录请求参数
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Remember bool   `json:"remember"`
}

// AuthController 认证控制器
type AuthController struct {
	db *gorm.DB
}

// NewAuthController 创建认证控制器
func NewAuthController(db *gorm.DB) *AuthController {
	return &AuthController{db: db}
}

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录接口
// @Tags 认证模块
// @Accept json
// @Produce json
// @Param body body LoginRequest true "登录参数"
// @Success 200 {object} response.Response
// @Router /auth/login [post]
func (ctrl *AuthController) Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.ParamError(c)
		return
	}

	// 查询用户
	var admin models.Admin
	if err := ctrl.db.Where("username = ?", req.Username).First(&admin).Error; err != nil {
		response.Error(c, 401, "用户名或密码错误")
		return
	}

	// 检查用户状态
	if admin.Status != 1 {
		response.Error(c, 401, "用户已被禁用")
		return
	}

	// 验证密码
	if !utils.CheckPasswordHash(req.Password, admin.Password) {
		response.Error(c, 401, "用户名或密码错误")
		return
	}

	// 预加载角色和权限
	if err := ctrl.db.Preload("Roles.Permissions").First(&admin, admin.ID).Error; err != nil {
		response.ServerError(c)
		return
	}

	// 生成token
	cfg, _ := config.LoadConfig()
	token, err := middleware.GenerateToken(&admin, cfg.JWTSecret)
	if err != nil {
		response.ServerError(c)
		return
	}

	// 构建响应数据
	userInfo := gin.H{
		"id":         admin.ID,
		"username":   admin.Username,
		"nickname":   admin.Nickname,
		"avatar":     admin.Avatar,
		"email":      admin.Email,
		"phone":      admin.Phone,
		"roles":      []string{},
		"permissions": []string{},
	}

	// 提取角色和权限
	var roles []string
	var permissions []string
	for _, role := range admin.Roles {
		roles = append(roles, role.Code)
		for _, permission := range role.Permissions {
			permissions = append(permissions, permission.Code)
		}
	}

	userInfo["roles"] = utils.UniqueString(roles)
	userInfo["permissions"] = utils.UniqueString(permissions)

	response.Success(c, gin.H{
		"token":    token,
		"userInfo": userInfo,
	})
}

// Current 获取当前用户信息
// @Summary 获取当前用户信息
// @Description 获取当前登录用户信息
// @Tags 认证模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} response.Response
// @Router /auth/current [get]
func (ctrl *AuthController) Current(c *gin.Context) {
	// 获取当前用户
	user, err := middleware.GetCurrentUser(c)
	if err != nil {
		response.Unauthorized(c)
		return
	}

	// 构建响应数据
	userInfo := gin.H{
		"id":         user.ID,
		"username":   user.Username,
		"nickname":   user.Nickname,
		"avatar":     user.Avatar,
		"email":      user.Email,
		"phone":      user.Phone,
		"roles":      []string{},
		"permissions": []string{},
	}

	// 提取角色和权限
	var roles []string
	var permissions []string
	for _, role := range user.Roles {
		roles = append(roles, role.Code)
		for _, permission := range role.Permissions {
			permissions = append(permissions, permission.Code)
		}
	}

	userInfo["roles"] = utils.UniqueString(roles)
	userInfo["permissions"] = utils.UniqueString(permissions)

	response.Success(c, userInfo)
}

// Logout 用户退出
// @Summary 用户退出
// @Description 用户退出登录
// @Tags 认证模块
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} response.Response
// @Router /auth/logout [post]
func (ctrl *AuthController) Logout(c *gin.Context) {
	// 在实际应用中，可以将token加入黑名单
	// 这里简单返回成功
	response.Success(c, nil)
}